package api

import (
	"gitee.com/ChangPaoZhe/devops/apps/command"
	"gitee.com/ChangPaoZhe/devops/apps/command/impl"
	"gitee.com/ChangPaoZhe/devops/apps/user"
	"gitee.com/ChangPaoZhe/devops/httpresponse"
	"gitee.com/ChangPaoZhe/devops/ioc"
	"gitee.com/ChangPaoZhe/devops/middleware"
	"github.com/gin-gonic/gin"
	"gitee.com/ChangPaoZhe/devops/apps/token"

)


type HttpCommand  struct {
	// 集成 interface 
	svc  command.Commander
}


func (c *HttpCommand)Name() string {
	return command.App_Name
}


func (c *HttpCommand)Registory(r  gin.IRouter){
	v1:=r.Group(command.App_Name)
	v1.Use(middleware.NewTokenAuther().Auth)
	v1.POST("/exec", middleware.Required(user.Role_ADMIN),c.Exec)
	v1.POST("/InsertParam", middleware.Required(user.Role_ADMIN),c.InsertParams)


}

func (c *HttpCommand) Init() error {
	c.svc=ioc.GetServer(command.App_Name).(command.Commander)
	return nil  
}


func  (c *HttpCommand)  Exec(r *gin.Context) {
	req:=impl.NewDefaultCommandInput()
	if err:=r.BindJSON(req);err!=nil {
		httpresponse.Failed(r,httpresponse.NewAuthFailed(err.Error()))
		return
	}
	resource,err:=c.svc.Exec(r.Request.Context(), req)
	if err!=nil  {
		httpresponse.Failed(r,httpresponse.NewAuthFailed(err.Error()))
		return
	}
	httpresponse.Success(r, resource)
}



func  (c *HttpCommand)  InsertParams(r *gin.Context) {
	tkObj := r.Keys[token.TOKEN_GIN_KEY_NAME]
	tk, _ := tkObj.(*token.Token)
	req:=impl.NewDefaultInput_Params()
	req.InserUser=tk.Username
	if err:=r.BindJSON(req);err!=nil {
		httpresponse.Failed(r,httpresponse.NewAuthFailed(err.Error()))
		return
	}
	resource,err:=c.svc.InsertParams(r.Request.Context(), req)
	if err!=nil  {
		httpresponse.Failed(r,httpresponse.NewAuthFailed(err.Error()))
		return
	}
	httpresponse.Success(r, resource)
}




func init(){
	ioc.RegisterHttp(&HttpCommand{})
}